<template>
	<view class="form-content">
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<view class="title">
			<view class="form-title" v-if="showFormTitle">
				<text class="left-line"></text>{{ formTitle }}
			</view>
			<slot v-if="showButton" name="buttonName"></slot>
		</view>
		<uni-forms ref="formRef" :modelValue="ruleForm">
			<view v-for="(item, index) in allFormConfig" :key="index" v-show="!item.hiddenItem">
				<uni-forms-item :name="item.key">
					<view slot="label" class="left-label">
						<text class="required-mark" v-if="getRequired(item)">*</text>
						<slot v-if="item.isLabelSlot" :name="item.labelSlot"></slot>
						<view v-else>{{ item.label }}</view>
					</view>
					<!-- input输入框 -->
					<view v-if="item.type==='input'" class="input-content">
						<uni-easyinput :ref="`${item.key}Input`" v-model="ruleForm[item.key]"
							:placeholder="item.suffixSlot ? '' : item.placeholder || `请输入${item.label}`"
							:disabled="item.isDisabled || false" :maxlength="item.maxLength"
							@blur="inputBlur($event, item)"></uni-easyinput>
					</view>
					<!-- select选择框 -->
					<uni-data-select class="you-select" v-if="item.type==='select'" v-model="ruleForm[item.key]"
						:localdata="optionsObj[item.key]" :placeholder="item.placeholder || `请选择${item.label}`"
						:disabled="item.isDisabled || false" @change="selectChange($event, item)"></uni-data-select>
					<!-- 时间选择器 -->
					<view class="left-label" v-if="item.type==='dateTime'" @click="show=true">
						<view style="color:#cfcfcf;font-size: 28rpx;font-family: PingFang SC;display: flex;">
							{{ ruleForm[item.key]? formatDate(ruleForm[item.key]) :formatDate(Date.now())}}
							<u-icon name="arrow-right" style="margin-left: 10rpx;" size="15"></u-icon>
						</view>
						<u-datetime-picker :show="show" mode="datetime" v-model="ruleForm[item.key]"
							:return-type="item.returnType || 'string'" :disabled="item.isDisabled || false"
							:formatter="formatter" @cancel="show=false" @confirm="timeChange($event, item)"
							:minDate="Date.now()"></u-datetime-picker>
						<!-- @change="timeChange($event, item)" -->
					</view>

					<!-- <uni-datetime-picker v-model="ruleForm[item.key]" v-if="item.type==='dateTime'"
						:type="item.dateType || 'datetime'" :return-type="item.returnType || 'string'"
						:disabled="item.isDisabled || false" :start="item.minDate" @change="timeChange($event, item)" /> -->
				</uni-forms-item>
			</view>
			<slot name="bottomBox"></slot>
		</uni-forms>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				allFormConfig: [],
				ruleForm: {},
				optionsObj: {}, // 所有数据的options数据
				rules: {},
				show: false
			}
		},
		props: {
			formTitle: {
				type: String,
				default: '表单标题'
			},
			formConfig: {
				type: Array,
				default: () => {
					return []
				}
			},
			value: {
				type: Object,
				default: () => {
					return {}
				}
			},
			showFormTitle: {
				type: Boolean,
				default: true
			},
			showButton: {
				type: Boolean,
				default: false
			},
			customValName: {
				type: String,
				default: ''
			}
		},
		watch: {
			formConfig: {
				handler(newVal, oldVal) {
					const formConfig = uni.$u.deepClone(newVal)
					formConfig.forEach(item => {
						if (item.type === 'select') {
							this.selectOptions(item)
						}
					})
					this.allFormConfig = uni.$u.deepClone(formConfig)
					this.getInitVal()
					this.getRules()
				},
				deep: true,
				immediate: true
			},
			value: {
				handler(newVal, oldVal) {
					if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
						this.ruleForm = {
							...this.ruleForm,
							...newVal
						}
					}
				},
				deep: true,
				immediate: true
			},
			ruleForm: {
				handler(newVal, oldVal) {
					if (!newVal) return
					this.$emit('input', newVal)
				},
				deep: true
			}
		},
		mounted() {
			const now = new Date();
			const oneMinute = 60 * 1024; // 一分钟的毫秒数
			const newDate = new Date(now.getTime() + oneMinute);
			this.ruleForm.chooseTime = newDate.getTime();
		},
		methods: {
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			// 获取校验规则
			getRules() {
				this.formConfig.forEach(item => {
					this.rules[item.key] = {}
					if (item.hiddenItem) return
					let itemRules = item.rules
					this.rules[item.key]['rules'] = itemRules
				})
				this.$nextTick(() => {
					if (this.$refs.formRef) {
						this.$refs.formRef.setRules(this.rules)
					}
				})
			},
			getRequired(item) {
				if (!item.rules) return false
				const required = item.rules.filter(item => item.required)
				return required.length
			},
			getInitVal() {
				this.formConfig.forEach(item => {
					if (this.ruleForm[item.key] !== null && this.ruleForm[item.key] !== undefined) {
						return
					}
					if (item.initVal !== null && item.initVal !== undefined) {
						this.ruleForm[item.key] = item.initVal
					}
				})
			},
			inputBlur($event, item) {
				this.$emit(item.key + 'Blur', $event.detail.value)
			},
			// 下拉框更改
			selectChange($event, item) {
				if (item.labelKey) {
					this.ruleForm[item.labelKey] = ''
					this.getSelectLabel($event, item)
				}
				if (item.selectKey) {
					this.$emit(item.selectKey + 'Change', $event, item)
				} else {
					this.$emit(item.key + 'Change', $event, item)
				}
			},

			timeChange($event, item) {
				console.log(this.formatDate($event.value), item, '$event, item');
				this.show = false
				this.$emit(item.key + 'Change', this.formatDate($event.value), item)
			},
			formatDate(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
			},
			selectOptions(item) {
				if (item.urlOptions && !(item.options && item.options.length)) {
					if (this.selectOptionsData[item.key]) return
					this.getUrlOptions(item)
				}
				if (item.options && item.options.length) {
					item.options = item.options
					this.optionsObj = {
						...this.optionsObj,
						[item.key]: item.options
					}
					if (item.labelKey && item.type === 'select') {
						const value = this.ruleForm[item.key]
						this.getSelectLabel(value, item)
					}
				}
			},
			getUrlOptions(item) {
				const params = item.urlOptions.params
				this.selectOptionsData[item.key] = true
				api_select[item.urlOptions.requestName](params).then(res => {
					if (item.urlOptions.dataLocal) {
						if (!res[item.urlOptions.dataLocal] || res[item.urlOptions.dataLocal].length === 0) return
						const options = this.getOptionsConfig(res[item.urlOptions.dataLocal], item, 'urlOptions')
						item.options = options
						this.optionsObj = {
							...this.optionsObj,
							[item.key]: item.options
						}
					} else {
						if (!res.rows || res.rows.length === 0) return
						const options = this.getOptionsConfig(res.rows, item, 'urlOptions')
						item.options = options
						this.optionsObj = {
							...this.optionsObj,
							[item.key]: item.options
						}
					}
					if (item.labelKey && item.type === 'select') {
						const value = this.ruleForm[item.key]
						this.getSelectLabel(value, item)
					}
				}).catch(err => {
					this.selectOptionsData[item.key] = false
				})
			},
			getOptionsConfig(data, dItem, keyLocal) {
				let resultData = []
				data.forEach(item => {
					if (item.children) {
						resultData.push({
							text: item[dItem[keyLocal].keys.text],
							value: item[dItem[keyLocal].keys.value],
							children: this.getOptionsConfig(item.children, dItem, keyLocal) || null
						})
					} else {
						resultData.push({
							text: item[dItem[keyLocal].keys.text],
							value: item[dItem[keyLocal].keys.value]
						})
					}
				})
				return resultData
			},
			// 下拉框文字数据
			getSelectLabel(val, item) {
				item.options.forEach(oItem => {
					if (val === oItem.value) {
						this.ruleForm[item.labelKey] = oItem.text
					}
				})
			},
			// 表单校验
			async checkFormData() {
				uni.showLoading()
				await this.getRules(true)
				return this.$refs.formRef.validate().then(valid => {
					uni.hideLoading()
					return true
				}).catch(err => {
					uni.hideLoading()
					return false
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
</style>